{% extends "base.html" %}

{% block content %}
    <div class="container-fluid">
        <div class="row clearfix">

            <form id="form-submitsql" action="/autoreview/" method="post" class="form-horizontal" role="form">
                {% csrf_token %}
                <input type="hidden" id="workflowid" name="workflowid"/>
                <div class="col-md-9 column">
                    <pre id="sql_content_editor" style="min-height:400px"></pre>
                </div>
                <div style="display: none" class="col-md-8 column">
                    <textarea id="sql_content" name="sql_content" class="form-control" data-name="SQL内容"
                              placeholder="请在此提交SQL，请以分号结尾。例如：use test; create table t1(id int)engine=innodb;" rows=20
                              required></textarea>
                </div>

                <div class="col-md-3 column">
                    <div class="form-group">
                        <input id="sql-upload" name="sql-upload" accept=".sql" type="file" class="file-loading">
                    </div>
                    <div class="form-group">
                        <input id="workflow_name" type="text" name="workflow_name" class="form-control"
                               data-name="上线单名称" placeholder="请输入上线单名称，如:XX项目会员功能建表" required>
                    </div>
                    <div class="form-group">
                        <select id="cluster_name" name="cluster_name"
                                class="selectpicker show-tick form-control bs-select-hidden" data-name="要上线的集群"
                                data-live-search="true" data-placeholder="请选择要上线的集群:" required>
                            <option value="is-empty" disabled="" selected="selected">请选择要上线的集群:</option>
                            {% for cluster_name,dbs in dictAllClusterDb.items %}
                                <option value="{{ cluster_name }}">{{ cluster_name }}集群 (包含db：
                                    {% for db in dbs %}
                                        {{ db }}{% if not forloop.last %},{% endif %}
                                    {% endfor %}
                                    )
                                </option>
                            {% endfor %}

                        </select>
                    </div>
                    <div class="form-group">
                        <select id="is_backup" name="is_backup"
                                class="selectpicker show-tick form-control bs-select-hidden" data-name="是否选择备份"
                                data-placeholder="请选择是否要备份:" required>
                            <option value="is-empty" disabled="" selected="selected">请选择是否要备份:</option>
                            <option value="是">是</option>
                            <option value="否">否</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <select id="review_man" name="review_man"
                                class="selectpicker show-tick form-control bs-select-hidden" data-name="审核人"
                                data-live-search="true" data-placeholder="请选择RD审核人:" required>
                            <option value="is-empty" disabled="" selected="selected">请选择审核人:</option>
                            {% for man in reviewMen %}
                                <option value="{{ man }}">{{ man }}</option>
                            {% endfor %}
                        </select>
                    </div>
                    <!--增加副审核人选项-->
                    <div class="form-group">
                        <div class="panel-group" id="accordion">
                            <div class="panel panel-default">
                                <div class="panel-heading">
                                    <h4 class="panel-title">
                                        <a data-toggle="collapse"
                                           data-parent="#accordion"
                                           href="#collapseOne">
                                            <i class="glyphicon-plus
                                        glyphicon"></i>
                                            增加副审核人（可选)
                                        </a>
                                    </h4>
                                </div>
                                <div id="collapseOne" class="panel-collapse
                            collapse">
                                    <div class="panel-body" style="margin-left:
                                25px">
                                        {% for man in reviewMen %}
                                            <div class="radio" id="{{ man }}">
                                                <input type="radio" id="radio1"
                                                       name="sub_review_man" value="{{ man }}"/>
                                                <label for="radio1"> {{ man }}
                                                </label>
                                            </div>
                                        {% endfor %}
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="form-group">
                        <input id="btn-format" type="button" class="btn btn-info" value="美化"/>
                        <input type="button" id="btn-autoreview" class="btn btn-danger" value="SQL检测"/>
                        {#                        <button type="reset" id="btn-reset" class="btn btn-warning">清空选项</button>#}
                        <input id="btn-submitsql" type="button" class="btn btn-success" value="SQL提交"/>
                    </div>
                </div>
            </form>
        </div>
        <!-- 审核结果 -->
        <table id="inception-result" data-toggle="table" class="table table-striped table-hover"
               style="display: none"></table>
        <!-- 审核信息确认 -->
        <div class="modal fade" id="submitComfirm" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
            <div class="modal-dialog" role="document">
                <div class="modal-content">
                    <div class="modal-header ">
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
                                aria-hidden="true">×</span></button>
                        <h4 class="modal-title text-danger">提交信息确认</h4>
                    </div>
                    <div class="modal-body">
                        <p>提交的SQL经检测仍存在<font color="red" size="5"><b id="CheckWarningCount"></b></font>个警告信息和<font
                                color="red" size="5"><b id="CheckErrorCount"></b></font>个错误信息<br>
                            请按照平台规范仔细检查！<br>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-info" data-dismiss="modal">取消</button>
                        <button id="submitsqlcomfirm" type="button" class="btn btn-danger" data-dismiss="modal">确定提交
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>
{% endblock content %}
{% block js %}
    {% load staticfiles %}
    <link href="{% static 'fileinput/css/fileinput.min.css' %}" rel="stylesheet">
    <script src="{% static 'ace/ace.js' %}"></script>
    <script src="{% static 'ace/ext-language_tools.js' %}"></script>
    <script src="{% static 'ace/mode-sql.js' %}"></script>
    <script src="{% static 'ace/theme-github.js' %}"></script>
    <script src="{% static 'ace/snippets/sql.js' %}"></script>
    <script src="{% static 'ace/ace_init.js' %}"></script>
    <script src="{% static 'fileinput/js/fileinput.min.js' %}"></script>
    <script src="{% static 'fileinput/js/locales/zh.js' %}"></script>
    <script src="{% static 'user/js/autoreview.js' %}"></script>
    <script src="{% static 'dist/js/sql-formatter.min.js' %}"></script>

    <!--upload -->
    <script>
      //初始化上传控件
        function init_upload() {
            $("#sql-upload").fileinput({
                language: 'zh',
                allowedFileExtensions: ['sql'],//接收的文件后缀
                showCaption: true,//是否显示标题
                initialCaption: '仅支持10M内的SQL文件',
                defaultPreviewContent: '仅支持10M内的SQL文件',
                showUpload: false,     //不显示上传按钮
                showPreview: false,    // 不显示预览,
                maxFileSize: 10240
            }).on('fileloaded', function () {
                loadsql();
            })
                .on('fileclear', function (event) {
                    editor.setValue("");
                });
        }

        //读取文件并展示在输入域
        function loadsql() {
            //获取文件
            var file = $("#sql-upload")[0].files[0];

            //创建读取文件的对象
            var reader = new FileReader();

            //创建文件读取相关的变量
            var sqlFile;

            //为文件读取成功设置事件
            reader.onload = function (e) {
                var sqlFile = e.target.result;
                var value = editor.getValue() + sqlFile;
                editor.setValue(value);
                editor.clearSelection();

            };

            //正式读取文件
            reader.readAsText(file);
        }
    </script>
    <!--ace -->
    <script>
        // 集群变更获取数据库补全提示
        $("#cluster_name").change(function () {
            //将数据通过ajax提交给获取db_name
            $.ajax({
                type: "post",
                url: "/getdbNameList/",
                dataType: "json",
                data: {
                    cluster_name: $("#cluster_name").val(),
                    is_master: true
                },
                complete: function () {
                },
                success: function (data) {
                    if (data.status === 0) {
                        var result = data.data;
                        var dbs = [];
                        for (var i = 0; i < result.length; i++) {
                            dbs.push({
                                name: result[i],
                                value: result[i],
                                caption: result[i],
                                meta: 'databases',
                                score: '100'
                            })
                        }
                        //自动补全提示
                        setCompleteData(dbs)
                    } else {
                        alert("status: " + data.status + "\nmsg: " + data.msg + data.data);
                    }
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    alert(errorThrown);
                }
            });
        });
    </script>
    <!--validate -->
    <script>
        function validateForm(element) {
            var result = true;
            element.find('[required]').each(
                function () {
                    var fieldElement = $(this);
                    //如果为null则设置为''
                    var value = fieldElement.val() || '';
                    if (value) {
                        value = value.trim();
                    }
                    if (!value || value === fieldElement.attr('data-placeholder')) {
                        alert((fieldElement.attr('data-name') || this.name) + "不能为空！");
                        result = false;
                        return result;
                    }
                }
            );
            return result;
        }

        //格式化sql
        $("#btn-format").click(function () {
                var select_sqlContent = editor.session.getTextRange(editor.getSelectionRange());
                if (select_sqlContent) {
                    var sqlContent = select_sqlContent
                }
                else {
                    var sqlContent = editor.getValue();

                }
                var sqlContent = window.sqlFormatter.format(sqlContent);
                editor.setValue(sqlContent);
                editor.clearSelection();
            }
        );

        $("#btn-submitsql").click(function () {
            //获取form对象，判断输入，通过则提交
            var formSubmit = $("#form-submitsql");
            var sqlContent = editor.getValue();
            $("#sql_content").val(sqlContent);
            if (validateForm(formSubmit)) {
                //判断是否需要弹出提示
                var CheckWarningCount = sessionStorage.getItem('CheckWarningCount');
                var CheckErrorCount = sessionStorage.getItem('CheckErrorCount');
                $("#CheckWarningCount").text(CheckWarningCount);
                $("#CheckErrorCount").text(CheckErrorCount);
                if (CheckWarningCount > 0 || CheckErrorCount > 0) {
                    $('#submitComfirm').modal('show');
                }
                else {
                    formSubmit.submit();
                    $('input[type=button]').addClass('disabled');
                    $('input[type=button]').prop('disabled', true);
                }
            }
        });

        $("#submitsqlcomfirm").click(function () {
            //获取form对象，判断输入，通过则提交
            var formSubmit = $("#form-submitsql");
            var sqlContent = editor.getValue();
            $("#sql_content").val(sqlContent);
            formSubmit.submit();
            $('input[type=button]').addClass('disabled');
            $('input[type=button]').prop('disabled', true);
        });

        $("#btn-reset").click(function () {
            editor.setValue("");
            //重置选择器
            $(".selectpicker").selectpicker('val', '');
            $(".selectpicker").selectpicker('render');
            $(".selectpicker").selectpicker('refresh');
        });

        $("#review_man").change(function review_man() {
            var review_man = $(this).val();
            $("div#" + review_man).hide();
        });
    </script>
    <!--init -->
    <script>
        $(document).ready(function () {
            // 初始化上传控件
            init_upload();
            // 提示信息
            //editor.setValue("请在此提交SQL，请以分号结尾。例如：use test; create table t1(id int)engine=innodb;");
            //editor.clearSelection();
            // 禁用提交按钮，点击检测后才激活
            $("#btn-submitsql").addClass('disabled');
            $("#btn-submitsql").prop('disabled', true);

            var pathname = window.location.pathname;
            if (pathname == "/editsql/") {
                $("#workflowid").val(sessionStorage.getItem('editWorkflowDetailId'));
                $("#workflow_name").val(sessionStorage.getItem('editWorkflowNname'));
                editor.setValue(sessionStorage.getItem('editSqlContent'));
                editor.clearSelection();
                $("#cluster_name").val(sessionStorage.getItem('editClustername'));
                $("#is_backup").val(sessionStorage.getItem('editIsbackup'));
                $("#review_man").val(sessionStorage.getItem('editReviewman'));
                var sub_review_name = sessionStorage.getItem('editSubReviewman');
                $("input[name='sub_review_man'][value=\'" + sub_review_name + "\']").attr("checked", true);
            }
            else if (pathname === "/submitothercluster/") {
                $("#workflow_name").val(sessionStorage.getItem('editWorkflowNname'));
                editor.setValue(sessionStorage.getItem('editSqlContent'));
                editor.clearSelection();
                $("#is_backup").val(sessionStorage.getItem('editIsbackup'));
                $("#review_man").val(sessionStorage.getItem('editReviewman'));
                var sub_review_name = sessionStorage.getItem('editSubReviewman');
                $("input[name='sub_review_man'][value=\'" + sub_review_name + "\']").attr("checked", true);
            }
        });
    </script>
{% endblock %}
